/**
*      author: Y_Yao
*      created: 2024-10-26 20:49:47
**/

#include<bits/stdc++.h>

using namespace std;
#define int LL
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
int mod = 1e9 + 7;
int n,k;

void solve()
{
    cin >> n >> k;

    int t1 = 1,t2 = 1;
    int i = 2;
    int cur = 0;
    if(k == 1)
    {
        cout << n % mod << endl;
        return;
    }
    while(1)
    {
        cur = (t1 + t2) % k;
        i++;
        if(cur == 0) break;
        t1 = t2;
        t2 = cur;
    }

    int ret = ((i % mod) * (n % mod)) % mod;
    cout << ret << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}